package com.itheima.reggie.filter;


import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //定义无需校验的url
    private static final String[] checks = new String[]{
            "/employee/login",
            "/employee/logout",
            "/backend/**",
            "/front/**",
            "/user/sendMsg",
            "/user/login",
            "/doc.html",
            "/webjars/**",
            "/swagger-resources",
            "/v2/api-docs"
    };

    //路径匹配器,支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取本次请求的URI
        String uri = request.getRequestURI();

        //2.判断本次请求是否需要处理
        boolean reuslt = checkUri(uri);

        //3.如果不需要处理,则直接放行
        if (!reuslt) {
            log.info("请求的URI:{},无需校验,直接放行", uri);
            filterChain.doFilter(request, response);
            return;
        }

        //4.判断登录状态,如果已经登录,则直接放行  --后端
        if (request.getSession().getAttribute("employee") != null) {
            log.info("请求的URI是:{},用户已登录,直接放行",request.getRequestURI());

            //获取session中当前用户登录的id,并且将其存入ThreadLocal中
            Long employeeId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(employeeId);

            filterChain.doFilter(request, response);
            // 删除ThreadLocal中的值,以免发生内存泄漏
            BaseContext.removeCurrentId();
            return;
        }


        //判断登录状态,如果已经登录,则放行   --前台
        if (request.getSession().getAttribute("user") != null) {
            log.info("请求的URL是:{}", request.getRequestURI());

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request, response);
            BaseContext.removeCurrentId();

            return;
        }



        //5.如果未登录就返回登录页面
        log.info("请求的URI是:{},如果用户未登录,就跳转到登录页面", uri);
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
        return;
    }


    /**
     *
     * @param uri 需要检测的URI
     * @return 是否需要校验,true:校验 ,false : 不需要校验
     */
    private boolean checkUri(String uri) {
        for (String check : checks) {
            if (PATH_MATCHER.match(check, uri)) {
                return false;
            }
        }
        return true;
    }
}
